package com.m1905hd.user.web.controller
import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.Page
import com.m1905hd.user.service.DynamicService
import com.m1905hd.user.web.PKUtil
import com.mongodb.BasicDBObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
/**
 * Created with IDEA
 * User:hxh
 * Date:16/4/22
 * Time:上午9:47
 */
@Controller
@RequestMapping("dynamic")
class DynamicController {

    @Autowired
    DynamicService dynamicService

    @RequestMapping("list")
    def showList() {
        return "dynamic/list"
    }

    @RequestMapping(value = "/list.json")
    def list(
            @RequestParam(defaultValue = "15") int limit,
            @RequestParam(defaultValue = "0") int pageIndex,
            String title
    ) {
        def query = new BasicDBObject()
        if (!StringUtils.isEmpty(title)) {
            query.append("title", ~/${title}/)
        }
        pageIndex = pageIndex + 1
        Page page = this.dynamicService.list(query, new BasicDBObject("created", 1), null, pageIndex, limit)
        [results: page.count, rows: page.data]
    }


    @RequestMapping(value = "edit", method = RequestMethod.POST)
    def edit(
            @RequestParam(defaultValue = "0") int id, String title,int status, String img,@RequestParam(defaultValue = "") int newsId,int type
    ) {
        def obj = [title: title,status: status, img: img, newsId: newsId,type:type] as BasicDBObject
        if (id == 0) {
            obj.created = System.currentTimeMillis()
            id = this.dynamicService.getCurrentId()
        }
        this.dynamicService.update(id, obj)
        return "redirect:list"
    }

    @RequestMapping("delete.json")
    def del(String ids) {
        PKUtil.buildIds(ids).each {
            this.dynamicService.del(it)
        }
        return [code: JSONCode.SUCCESS.code]
    }
}
